package dev.tools;

import java.io.*;
import java.util.*;

public class IndexToIntWriter {

    public IndexToIntWriter(String indexFileName) {
        this.indexFileName = indexFileName;
    }

    public int[] toIntArray() {
        performProcess();
        return processedResult;
    }
    
    private void performProcess() {
        if (processedResult == null) {
            process();
        }
    }

    private void process() {
        List<String> lines = readAllLinesOfFile();

        processedResult = new int[lines.size()];

        for (int item = 0; item < processedResult.length; item++) {
            processedResult[item] = convertToInt(lines.get(item));
        }
    }

    private List<String> readAllLinesOfFile() {
        IndexFileLoader loader = new IndexFileLoader(indexFileName);
        return loader.load();
    }

    private int convertToInt(String line) {
        return TextToNumberConverter.toInt(line);
    }

    public List<Integer> toListOfIntegers() {
        performProcess();
        ArrayList<Integer> result = new ArrayList<Integer>(
                processedResult.length);
        for (int number : processedResult) {
            result.add(Integer.valueOf(number));
        }
        return result;
    }

    public void writeResultToFile(String fileName)
            throws FileNotFoundException, IOException {
        makeWriter(fileName);
        write();
        closeWriter();
    }

    private void write() throws IOException {
        performProcess();
        int totalLines = processedResult.length;
        writer.writeInt(totalLines);

        for (int line : processedResult) {
            writer.writeInt(line);
        }
    }

    private void makeWriter(String fileName) throws FileNotFoundException {
        FileOutputStream fis = new FileOutputStream(fileName);
        BufferedOutputStream bis = new BufferedOutputStream(fis);
        writer = new DataOutputStream(bis);
    }

    private void closeWriter() throws IOException {
        writer.flush();
        writer.close();
    }

    private int[] processedResult;
    private DataOutputStream writer;
    private final String indexFileName;
}
